﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Text;
using BaseData.Common;
using BaseData;
using BaseData.UI;
using TaxEntity.User;
using TaxBiz.User;
using System.IO;

namespace Admin.BaseCommon
{
    public class BasePage : BaseData.UI.PageContext
    {
        /// <summary>
        /// 用户编号
        /// </summary>
        protected int UserID = 0;
        /// <summary>
        /// 用户名
        /// </summary>
        protected string UserName = string.Empty;
        /// <summary>
        /// 姓名
        /// </summary>
        protected string sName = string.Empty;
        /// <summary>
        /// 用户类别
        /// </summary>
        protected UserType UserTypeLogin = UserType.SysManager;
        /// <summary>
        /// 用户类别（新权限）
        /// </summary>
        protected int UserPowerType = 0;
        /// <summary>
        /// 用户信息
        /// </summary>
        protected UserEntity UserLogin = null;
        /// <summary>
        /// 文件版本号
        /// </summary>
        public static string FileVersion = GetConfig("FileVersion");
        /// <summary>
        /// 加密密钥
        /// </summary>
        private static string encryptKey = "shizirho";
        /// <summary>
        /// 登陆用户部门编号
        /// </summary>
        protected int LoginDepartmentID = 0;
        /// <summary>
        /// 是否只能查看本部门数据
        /// </summary>
        protected bool isQueryDepartmentOnly = false;
        /// <summary>
        /// 是否有删除/修改数据权限
        /// </summary>
        protected bool isHasOptDataPower = false;



        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.init();
            this.Error += new System.EventHandler(Page_Error);
        }


        public void init()
        {
            bool isAuth = BaseData.Common.ComputerInfo.IsAuthorization(false);
            if (!isAuth)
            {
                Response.Write("<center>");
                Response.Write("<br/><br/><br/><br/><br/><br/><br/>");
                Response.Write("服务器未经过授权在使用软件<br/><br/>");
                Response.Write("请与系统管理员联系<br/><br/>");
                Response.Write("或者发邮件至sunllly@139.com购买授权<br/><br/>");
                Response.Write("</center>");
                Response.End();
            }

            string redirecturl = "/Admin/Login.aspx";
            string password = string.Empty;

            if (Request.Cookies["loginid"] != null && Request.Cookies["loginid"].Value != string.Empty
                && Request.Cookies["loginusername"] != null && Request.Cookies["loginusername"].Value != string.Empty
                && Request.Cookies["loginpassword"] != null && Request.Cookies["loginpassword"].Value != string.Empty
                && Request.Cookies["loginvalidation"] != null && Request.Cookies["loginvalidation"].Value != string.Empty)
            {
                int.TryParse(Request.Cookies["loginid"].Value, out UserID);
                UserName = Server.UrlDecode(Request.Cookies["loginusername"].Value);
                password = DESEncrypt.Decrypt(Request.Cookies["loginpassword"].Value, encryptKey);
                string validation = Request.Cookies["loginvalidation"].Value;
                if (validation == EncryptCookie(UserName, UserID.ToString()))
                {
                    if (Request.Cookies["usertype"] != null && Request.Cookies["usertype"].Value != string.Empty)
                    {
                        UserTypeLogin = (UserType)Enum.Parse(typeof(UserType), Request.Cookies["usertype"].Value, true);
                    }
                    UserloginCookie(UserName, UserID.ToString(), password, UserTypeLogin);
                }
                else
                {
                    UserID = 0;
                    UserName = string.Empty;
                }
            }

            if (UserID > 0)
            {
                UserLogin = new UserBiz().GetEntityById(UserID);
                if (UserLogin != null && UserLogin.UserId > 0)
                {
                    UserTypeLogin = UserLogin.UserEType;
                    UserName = UserLogin.UserName;
                    UserPowerType = UserLogin.UserType.Value;
                    sName = UserLogin.SName;
                    LoginDepartmentID = UserLogin.DepartmentID;
                    //判断哪些帐号只能查看本部门数据
                    if (UserTypeLogin == UserType.FenJuZhang || UserTypeLogin == UserType.ShuiShouManager)
                    {
                        isQueryDepartmentOnly = true;
                    }
                    isHasOptDataPower = this.HasOptDataPower();
                }
                else
                {
                    Jscript.AlertAndRedirectParent("请先登录！", redirecturl);
                    Response.End();
                }
            }
            else
            {
                Jscript.AlertAndRedirectParent("请先登录！", redirecturl);
                Response.End();
            }
        }

        void Page_Error(object sender, System.EventArgs e)
        {
            try
            {
                Exception ex = Server.GetLastError().GetBaseException();
                BaseData.Common.LogerHelper.WriteError(ex);
            }
            catch
            { }
            finally
            {
                //Server.ClearError();
            }
        }

        /// <summary>
        /// 用户是否具有操作数据权限
        /// </summary>
        public bool HasOptDataPower()
        {
            bool isHasPower = false;
            if (UserTypeLogin == UserType.ShuiShouManager || UserTypeLogin == UserType.ShuizhengKezhang
                 || UserTypeLogin == UserType.SuperManager)
            {
                isHasPower = true;
            }
            return isHasPower;
        }

        /// <summary>
        /// 用户是否具有权限
        /// </summary>
        public bool HasPower()
        {
            return PowerInfoBiz.HasPower(UserPowerType);
        }

        /// <summary>
        /// 用户是否具有权限
        /// </summary>
        public bool HasPower(string url)
        {
            return PowerInfoBiz.HasPower(UserPowerType, url);
        }

        /// <summary>
        /// 绑定Select
        /// </summary>
        protected void BindSelect(HtmlSelect select, DataTable dt, string text, string value, bool isInsertTips, params string[] selectedValue)
        {
            select.DataSource = dt;
            select.DataTextField = text;
            select.DataValueField = value;
            select.DataBind();
            if (isInsertTips)
            {
                //插入请选择
                select.Items.Insert(0, new ListItem("请选择", ""));
            }
            select.SelectedIndex = select.Items.IndexOf(select.Items.FindByValue(selectedValue[0]));
        }

        /// <summary>
        /// 输出Select内容
        /// </summary>
        /// <param name="dt">数据DataTable</param>
        /// <param name="text">显示文本</param>
        /// <param name="value">value</param>
        /// <param name="checkValue">选中value</param>
        /// <returns>Select内容</returns>
        protected string OutputSelectOptions(DataTable dt, string text, string value, params string[] checkValue)
        {
            StringBuilder sb = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    string checkStatus = string.Empty;
                    if (checkValue != null && checkValue.Length >0 && dr[value].ToString() == checkValue[0])
                    {
                        checkStatus = " selected=\"selected\"";
                    }
                    sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>", dr[value], dr[text], checkStatus);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 输出所属年份select
        /// </summary>
        /// <param name="year">选中年份</param>
        protected string CreateYear(int? year)
        {
            string selectDataTemplate = "<option value='{0}'>{1}</option>";
            int nowYear = DateTime.Now.Year;
            StringBuilder sb = new StringBuilder();
            int selYear = year.HasValue ? (year.Value == 0 ? nowYear : year.Value) : 0;
            if (!year.HasValue)
            {
                sb.AppendFormat(selectDataTemplate, "", "请选择税款属期");
            }
            for (int i = 0; i < 8; i++)
            {
                int optionYear = nowYear - 2 + i;
                if (optionYear == selYear)
                {
                    sb.AppendFormat(selectDataTemplate.Replace("<option", "<option selected='selected'"), optionYear, optionYear.ToString() + "年");
                }
                else
                {
                    sb.AppendFormat(selectDataTemplate, optionYear, optionYear.ToString() + "年");
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 格式化数据
        /// </summary>
        /// <param name="obj">源数据</param>
        /// <param name="pattern">格式化字符串</param>
        /// <returns>格式化后的数据</returns>
        public static string FormatData<T>(object obj, string pattern)
        {
            string retString = string.Empty;
            if (obj != null && obj != DBNull.Value)
            {
                if (typeof(T) == typeof(DateTime))
                {
                    DateTime t;
                    if (DateTime.TryParse(obj.ToString(), out t))
                    {
                        retString = t.ToString(pattern);
                    }
                }
                if (typeof(T) == typeof(double))
                {
                    double t;
                    if (double.TryParse(obj.ToString(), out t))
                    {
                        retString = t.ToString(pattern);
                    }
                }
            }
            return retString;
        }

        /// <summary>
        /// 写用户登录Cookie
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userID">用户ID</param>
        /// <param name="password">用户密码</param>
        /// <param name="userType">用户权限</param>
        public static void UserloginCookie(string userName, string userID, string password, UserType userType)
        {
            //string cookieDomain = GetConfig("Domain");
            DateTime cookieDate = DateTime.Now.AddHours(12);
            //userName
            System.Web.HttpContext.Current.Response.Cookies["loginname"].Value = System.Web.HttpContext.Current.Server.UrlEncode(userName);
            //System.Web.HttpContext.Current.Response.Cookies["loginname"].Domain = cookieDomain;
            System.Web.HttpContext.Current.Response.Cookies["loginusername"].Value = System.Web.HttpContext.Current.Server.UrlEncode(userName);
            //System.Web.HttpContext.Current.Response.Cookies["loginusername"].Domain = cookieDomain;
            HttpContext.Current.Response.Cookies["loginusername"].Expires = cookieDate;
            //userID
            System.Web.HttpContext.Current.Response.Cookies["loginid"].Value = System.Web.HttpContext.Current.Server.UrlEncode(userID);
            //System.Web.HttpContext.Current.Response.Cookies["loginid"].Domain = cookieDomain;
            //password
            System.Web.HttpContext.Current.Response.Cookies["loginpassword"].Value = BaseData.Common.DESEncrypt.Encrypt(password, encryptKey);
            //System.Web.HttpContext.Current.Response.Cookies["loginpassword"].Domain = cookieDomain;
            //写userType
            HttpContext.Current.Response.Cookies["usertype"].Value = ((int)userType).ToString();
            //HttpContext.Current.Response.Cookies["usertype"].Domain = cookieDomain;
            HttpContext.Current.Response.Cookies["usertype"].Expires = cookieDate;
            //validation
            System.Web.HttpContext.Current.Response.Cookies["loginvalidation"].Value = EncryptCookie(userName, userID);
            //System.Web.HttpContext.Current.Response.Cookies["loginvalidation"].Domain = cookieDomain;
        }

        /// <summary>
        /// 加密用户名和用户编号
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userID">用户编号</param>
        /// <returns>加密字符串</returns>
        public static string EncryptCookie(string userName, string userID)
        {
            int length = userName.Length;
            string encrypt = userName.Substring(0, length - 1) + "囧" + userID + userName.Substring(length - 1);
            string key = "stonnyer";
            return BaseData.Common.DESEncrypt.Encrypt(encrypt, key);
        }
    }
}